import re
import requests
import util

logger = util.logger('../static/网易云热歌榜')

base_url = 'https://music.163.com/discover'

toplist_url = base_url + '/toplist?id=3778678'

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
}
logger.info('开爬。。。。。。')
response = requests.get(toplist_url, headers=headers)
print(response.text)
results = re.findall(r'<a href="/song\?id=(\d{1,10})">(.*?)</a>', response.text)

music_base_url = 'https://music.163.com'
for result in results:
    detail_url = music_base_url + f'/song?id={result[0]}'
    name = result[1]
    print(detail_url, name)
    logger.info(f'开始访问 {name} 详情页')
    music_response = requests.get(detail_url, headers=headers)
    img_url = re.search(r'<meta property="og:image" content="(.*?)" />', music_response.text).group(1)
    print(img_url)
    logger.info('开始爬取音乐封面')
    img_response = requests.get(img_url, headers=headers)
    with open(f'../static/网易云热歌榜/img/{name}.jpg', 'wb') as f:
        f.write(img_response.content)
    logger.info(f'{name}请求成功')
    break

logger.info('over')
